package com.asen.commons.core.jdbc.result;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 结果集处理器容器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-05
 */
public class ResultProcessorRegistry {

    private final static Map<Class<?>, Set<ResultProcessor>> RESULT_PROCESSOR_MAP = new ConcurrentHashMap<Class<?>, Set<ResultProcessor>>();

    public static Set<ResultProcessor> getProcessors(Class<?> clazz) {
        Set<ResultProcessor> set = new HashSet<>();

        for (Map.Entry<Class<?>, Set<ResultProcessor>> entry : RESULT_PROCESSOR_MAP.entrySet()) {
            if (entry.getKey().isAssignableFrom(clazz)) {
                set.addAll(RESULT_PROCESSOR_MAP.get(entry.getKey()));
            }
        }

        return set;
    }

    public static void register(Class<?> clazz, ResultProcessor processor) {
        if (clazz == null || processor == null) {
            return;
        }

        synchronized (clazz) {
            Set<ResultProcessor> set = RESULT_PROCESSOR_MAP.get(clazz);
            if (set == null) {
                set = new HashSet<ResultProcessor>();
                RESULT_PROCESSOR_MAP.put(clazz, set);
            }
            set.add(processor);
        }
    }
}
